<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-02 19:42:06
 * @LastEditTime: 2023-08-05 15:42:06
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Repositories;

use App\Models\MarketOrder;
use App\Models\MarketOrderDetails;

/**
 * @property MarketOrderDetails $detail
 */
class MarketOrderRepository extends Repositories
    {
    protected $relation_models = ['department', 'process', 'status', 'process_route', 'customer', 'singler', 'linkman', 'creator', 'updator', 'salesman', 'attachments'];
    public function boot(MarketOrder $model, MarketOrderDetails $detail)
        {
        $this->model  = $model;
        $this->detail = $detail;
        }
    public function setPlanQuantity($id, $plan_quantity)
        {
        $detail = $this->detail->whereId($id)->first();
        if ($detail) {
            $main                  = $detail->main;
            $detail->plan_quantity += $plan_quantity;
            $main->plan_quantity += $plan_quantity;
            $detail->save();
            $main->save();
            }
        }
    /**
     * 订单交货
     * @param mixed $item_id 订单明细ID
     * @param mixed $quantity 交货数量
     * @return void
     * @author sunkaiyuan
     */
    public function delivery($item_id, $quantity)
        {
        $detail = $this->detail->whereId($item_id)->first();
        if ($detail) {
            $this->updateDelivery($detail, $quantity);
            $this->updateDelivery($detail->main, $quantity);
            }
        }
    private function updateDelivery($model, $quantity)
        {

        $model->delivery_quantity -= $quantity;
        if ($model->delivery_quantity <= 0) {
            $model->status_id = 2;
            }
        $model->save();
        }

    }